require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const { logger } = require('./utils/logger');
const db = require('./utils/db');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));

app.use(cors({
  origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : ['*'],
  credentials: true
}));

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 请求日志中间件
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.path}`, {
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });
  next();
});

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'OK',
    timestamp: new Date().toISOString(),
    service: 'second-hand-chat-backend'
  });
});

// API路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/chat', require('./routes/chat'));
app.use('/api/users', require('./routes/users'));

// 二手商城数据API路由
app.use('/api/sort', require('./routes/sort'));
app.use('/api/news', require('./routes/news'));
app.use('/api/home', require('./routes/home'));
app.use('/api/goods', require('./routes/goods'));
app.use('/api/categorys', require('./routes/categorys'));

// 新添加的数据API路由
app.use('/api/my', require('./routes/my'));
app.use('/api/cart', require('./routes/my_cart'));
app.use('/api/order', require('./routes/order'));
app.use('/api/find', require('./routes/find'));

// 图片上传路由
app.use('/api/upload', require('./routes/upload'));

// AI路由
app.use('/api/ai', require('./routes/ai'));

// 静态文件服务 - 在API路由之后配置，避免冲突

// 方案2：自定义中间件实现直接访问，但优先检查API路由
app.use((req, res, next) => {
  // 如果请求路径以/api开头，跳过静态文件处理
  if (req.path.startsWith('/api/')) {
    return next();
  }
  
  // 否则尝试提供静态文件
  express.static('public', {
    maxAge: '1d',
    etag: true,
    lastModified: true,
    index: false
  })(req, res, next);
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: 'Endpoint not found',
    path: req.originalUrl
  });
});

// 全局错误处理
app.use((error, req, res, next) => {
  logger.error('Unhandled error:', error);
  
  res.status(error.status || 500).json({
    error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error',
    ...(process.env.NODE_ENV === 'development' && { stack: error.stack })
  });
});

// 启动服务器
app.listen(PORT, async () => {
  logger.info(`🚀 Server is running on port ${PORT}`);
  logger.info(`📱 Chat backend service started`);
  
  // 检查数据库连接
  try {
    const connectionResult = await db.checkConnection();
    if (connectionResult.success) {
      logger.info('✅ Database connection successful');
    } else {
      logger.error('❌ Database connection failed:', connectionResult.message);
    }
  } catch (error) {
    logger.error('❌ Error checking database connection:', error);
  }
  
  // 检查腾讯云IM配置
  if (!process.env.TENCENT_CLOUD_SDK_APP_ID || !process.env.TENCENT_CLOUD_SECRET_KEY) {
    logger.warn('⚠️  腾讯云IM配置未完全设置，请检查环境变量');
  }
});

module.exports = app;